package com.gxuwz.endrskyweather;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.gxuwz.endrskyweather.model.ForecastDay;
import com.gxuwz.endrskyweather.viewmodel.WeatherForecastViewModel;

public class Weather7dFragment extends Fragment {
    private static final String ARG_CITY_NAME = "city_name";
    private static final String ARG_CITY_CODE = "city_code";
    private static final String TAG = "Weather7dFragment";
    private WeatherForecastViewModel viewModel;
    private boolean isObserverRegistered;

    public static Weather7dFragment newInstance(String cityName, String cityCode) {
        Weather7dFragment fragment = new Weather7dFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CITY_NAME, cityName);
        args.putString(ARG_CITY_CODE, cityCode);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                           @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.weather_7d, container, false);
        viewModel = new ViewModelProvider(requireParentFragment()).get(WeatherForecastViewModel.class);
        isObserverRegistered = false;
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Get container from layout
        HorizontalScrollView scrollView = view.findViewById(R.id.horizontal_scroll_view);
        LinearLayout container = (LinearLayout) scrollView.getChildAt(0);

        // Observe 7-day forecast data only once
        if (!isObserverRegistered) {
            viewModel.getDaily7dForecast().observe(getViewLifecycleOwner(), forecast -> {
                if (forecast != null && !forecast.isEmpty()) {
                    try {
                        // Clear previous views
                        container.removeAllViews();
                        // Create a view for each daily forecast
                        LayoutInflater inflater = LayoutInflater.from(requireContext());
                        for (ForecastDay day : forecast) {
                            View dailyView = inflater.inflate(R.layout.item_7d_forecast, container, false);

                            TextView dateView = dailyView.findViewById(R.id.tv_date);
                            TextView weatherView = dailyView.findViewById(R.id.tv_weather);
                            // 获取 item_7d_forecast.xml 中的控件：白天
                            ImageView weatherIconDayView = dailyView.findViewById(R.id.iv_weather_icon_day);
                            TextView tempMaxView = dailyView.findViewById(R.id.tv_temp_max);
                            TextView windDayView = dailyView.findViewById(R.id.tv_wind_day);
                            TextView windLevelDayView = dailyView.findViewById(R.id.tv_wind_level_day);
                            // 获取 item_7d_forecast.xml 中的控件：夜间
                            ImageView weatherIconNightView = dailyView.findViewById(R.id.iv_weather_icon_night);
                            TextView tempMinView = dailyView.findViewById(R.id.tv_temp_min);
                            TextView windNightView = dailyView.findViewById(R.id.tv_wind_night);
                            TextView windLevelNightView = dailyView.findViewById(R.id.tv_wind_level_night);
                            // 填充数据
                            dateView.setText(day.getTime());
                            weatherView.setText(day.getWeather());
                            // 白天天气的控件填充数据
                            weatherIconDayView.setImageResource(getResources().getIdentifier(day.getDayWeatherPic(), "drawable", requireContext().getPackageName()));
                            tempMaxView.setText(day.getTemperatureMax());
                            windDayView.setText(day.getWindDay());
                            windLevelDayView.setText(day.getWindPow());
                            // 夜间天气的控件填充数据
                            weatherIconNightView.setImageResource(getResources().getIdentifier(day.getNightWeatherPic(), "drawable", requireContext().getPackageName()));
                            tempMinView.setText(day.getTemperatureMin());
                            windNightView.setText(day.getWindNight());
                            windLevelNightView.setText(day.getWindPow());
                            // Add view to container
                            container.addView(dailyView);
                        }
                    } catch (Exception e) {
                        Toast.makeText(requireContext(), "数据加载失败", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "Failed to load 7-day forecast data:　", e);
                    }
                } else {
                    // Show error or empty state
                    Toast.makeText(requireContext(), "无法获取天气预报数据", Toast.LENGTH_SHORT).show();
                }
            });
            isObserverRegistered = true;
        }

        // 加载天气预报数据
        String cityCode = getArguments() != null ? getArguments().getString(ARG_CITY_CODE) : "";
        viewModel.loadDaily7dForecast(cityCode);

    }

}
